package com.mk.web.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.Logger;

import com.mk.web.dto.PageInfo;
import com.mk.web.model.Flower;
import com.mk.web.service.FlowerService;

/**
 * Created by WangChen on 2018/11/27 11:00.
 */
public class FlowerServiceImpl implements FlowerService {

    Logger logger = Logger.getLogger(FlowerServiceImpl.class);
    @Override
    public PageInfo<Flower> findByPage(int pageSize,int pageNumber) throws IOException {

        InputStream inputStream = Resources.getResourceAsStream("mybatis.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = factory.openSession();
        Map<String, Integer> param = new HashMap<>(2);
        param.put("pageSize", pageSize);
        param.put("pageStart", (pageNumber - 1) * pageSize);
        List<Flower> flowerList = sqlSession.selectList("a.b.c.selectByPage", param);
        long count = sqlSession.selectOne("a.b.c.selectCount");
        long total = count%pageSize == 0 ? count/pageSize : count/pageSize + 1;
        PageInfo<Flower> pageInfo = new PageInfo<>();
        pageInfo.setPageSize(pageSize);
        pageInfo.setPageNumber(pageNumber);
        pageInfo.setList(flowerList);
        pageInfo.setTotal(total);
        return pageInfo;
    }
}
